<script setup lang="ts">
defineOptions({name: 'RangePicker'});
import {computed, ref, useAttrs} from 'vue';
import dayjs, {Dayjs} from 'dayjs';
const attrs = useAttrs();
type RangeValue = [Dayjs, Dayjs];

type Props = {
  modelValue: any; // 响应式绑定的值
  type?: 'day' | 'month' | 'year';
  dayNum?: number; // 日
  monthNum?: number; // 月
  yearNum?: number; // 年
  selectType?: 'allDate' | 'prevDate' | 'nextDate'; // 设置可选日期 all: 全部； prev：今天之前日期不可选择； next: 今天之后日期不可选择
};

const props = withDefaults(defineProps<Props>(), {
  modelValue: undefined,
  type: 'day',
  dayNum: 3,
  monthNum: 1,
  yearNum: 1,
  selectType: 'nextDate',
});
const emit = defineEmits<{
  (e: 'update:modelValue', value: string): void;
}>();

const hackValue = computed({
  get: () => props.modelValue,
  set: (val) => {
    emit('update:modelValue', val);
  },
});

const dates = ref<RangeValue>();
const dateValue = ref<RangeValue>(props.modelValue);
// 今天之前日期不可选择  (过去日期)
const prevFun = (current: any) => {
  return current && current < dayjs().startOf(props.type);
};
// 今天之后日期不可选择  (未来日期)
const nextFun = (current: any) => {
  return current && current > dayjs().endOf(props.type);
};

const disabledDate = (current: Dayjs) => {
  if (!dates.value || (dates.value as any).length === 0) {
    if (props.selectType === 'prevDate') {
      return prevFun(current);
    }
    if (props.selectType === 'nextDate') {
      return nextFun(current);
    }
    return false;
  }
  // 日
  if (props.type === 'day') {
    const tooLate = dates.value[0] && current.diff(dates.value[0], 'days') > props.dayNum - 1;
    const tooEarly = dates.value[1] && dates.value[1].diff(current, 'days') > props.dayNum - 1;
    if (props.selectType === 'prevDate') {
      return prevFun(current) || tooEarly || tooLate;
    }
    if (props.selectType === 'nextDate') {
      return nextFun(current) || tooEarly || tooLate;
    }
    return tooEarly || tooLate;
  }
  // 月 年 props.type === 'month' || props.type === 'year'
  const tooLate = dates.value[0] && current.diff(dates.value[0], props.type) > props.monthNum - 1;
  const tooEarly = dates.value[1] && dates.value[1].diff(current, props.type) > props.monthNum - 1;
  if (props.selectType === 'prevDate') {
    return prevFun(current) || tooEarly || tooLate;
  }
  if (props.selectType === 'nextDate') {
    return nextFun(current) || tooEarly || tooLate;
  }
  return tooEarly || tooLate;
};

const onOpenChange = (open: boolean) => {
  if (open) {
    dates.value = [] as any;
    hackValue.value = [] as any;
  } else {
    hackValue.value = dateValue.value;

    console.log('关闭', open);
  }
};

const onChange = (val: any) => {
  dateValue.value = val;
};

const onCalendarChange = (val: any) => {
  dates.value = val;
};
</script>

<template>
  <a-range-picker
    :value="hackValue || dateValue"
    :disabled-date="disabledDate"
    v-bind="attrs"
    @change="onChange"
    @open-change="onOpenChange"
    @calendar-change="onCalendarChange"
  />
</template>
